import java.lang.reflect.Array;
import java.util.Arrays;

public class Method {
    public static void main(String[] args){
        //创建数组：
        int[] array1 = new int [3];//动态初始化
        //定义数组：
        int[] array2 ={1,2,3,4,5};//静态初始化
        //创建并定义：
        int[] array3 = new int[]{1,2,3};
        //数组遍历：
        for (int i = 0; i < array2.length ; i++) {
            System.out.println(array2[i]);
        }
        //for-each遍历
        for(int x : array2){
            System.out.println(x);
        }
        //引用赋值，数组指向同一个对象：
        array1[0] = 10;
        array1[1] = 20;
        array1[2] = 30;
        array2[0] = 100;
        array2[1] = 200;
        array1 = array2;
        array1[2] = 300;
        array2[3] = 400;
        array2[4] = 500;
        for (int i = 0; i < array2.length; i++) {
            System.out.println(array2[i]);
        }
        //交换数组地址值：
        int[] num1 = new int[]{1,2,3};
        int[] num2 = new int[]{4,5,6};
        System.out.println("交换前数组num1的元素分别为："+ Arrays.toString(num1));
        System.out.println("交换前数组num2的元素分别为："+ Arrays.toString(num2));
        int[] tmp = num1;
        num1 = num2;
        num2 = tmp;
        System.out.println("交换后数组num1的元素分别为："+ Arrays.toString(num1));
        System.out.println("交换后数组num2的元素分别为："+ Arrays.toString(num2));
        //null:
        /*int[] arr = null;
        System.out.println(arr[0]);
         */
        //参数传数组类型：
        int[] arr = {1,2,3};
        func(arr);
        System.out.println("arr[0]="+arr[0]);
        int[] array = test();
        System.out.println(Arrays.toString(array));
        //数组转字符串：
        int[] arr1 = {1,2,3,4,5,6};
        String newArr = Arrays.toString((arr1));
        System.out.println(newArr);
        int[] arr2 = {1,2,3,4};
        String ret = myToString(arr2);
        System.out.println(ret);
        double avg = avg(arr2);
        System.out.println(avg);
        System.out.println(find(arr2,4));
    }
    public static void func(int[] a){
        a[0] = 10;
        System.out.println("a[0]="+a[0]);
    }
    //返回值类型可以为数组：
    public static int[] test(){
        int[] ret = new int[2];
        ret[0] = 1;
        ret[1] = 2;
        return ret;
    }
    //函数：将数组转为字符串打印
    public static String myToString(int[] array){
        String ret = "[";
        for (int i = 0; i < array.length; i++) {
            ret += array[i];
            if(i != array.length-1){
                ret +=",";
            }
        }
        ret += "]";
        return ret;
    }
    //求数组中元素的平均值：
    public static double avg(int[] arr){
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum +=arr[i];
        }
        return (double)sum / arr.length;
    }
    //求、查找数组中指定元素-常规方法：
    public static int find(int[] arr,int data){
        for (int i = 0; i <arr.length ; i++) {
            if(arr[i] == data){
                return i;
            }
        }
        return -1;
    }
}
